<?php 
include "file.php";
  define('STRLENGTH', '6'); /*we declare a constante variable Corresponds Length of pseudo*/
		
	session_start();
	$_SESSION['username'] = $_POST['user']; /*we get back in $_SESSION['username'] the pseudo To use it in the other pages*/
setcookie('user', $_POST['user'], time() + 365*24*3600, null, null, false, true);
/*function which allows to verifie if pseudo Contains only charactersb between A Z or a z*/
	function verif_alpha($str){
	    preg_match("/([^A-Za-z])/",$str,$result);
	//We look tt for the characters other than [A-z] 
	    if(!empty($result)){
	//If we find character other than A-z
	        return false; 
	    }
	    return true;
	}



				

	if(!empty($_SESSION['username']))/*if session variale not empty*/
	{
 		
		if (!$fp = fopen("fichier.txt","r+")) /* we open file "fichier.txt"*/
		{
			echo "not opened";
			exit;
		}
		else
		{
			 $userI = fgets($fp,STRLENGTH+1);/*we get back line from the file*/
			 while(!feof($fp) && ($userI!=$_SESSION['username'])) /* while not at the end and then $userI not equal in session variale we get back line from the file*/
			{	
			  	$userI = fgets($fp,STRLENGTH+1);	
			
			}
								
				
			if($userI==$_SESSION['username']) /*if in the file there are The contents of session variale*/
			{
?>
				<script language="JavaScript">
					alert("pseudo already exist"); /*popup with javacript*/
					document.location.href = 'index.php';/*Rerouting in login page*/
				</script>
			<?php
			}
			else
			{	
				if(strlen($_SESSION['username'])==STRLENGTH && verif_alpha($_SESSION['username'])) /*else we verify if pseudo respect condition */
				{
							
					fputs($fp,$_SESSION['username']); /*whrite it in the file*/
	         			fputs($fp, "\n");
					header('location:chat.php');/*Rerouting in the chat page*/
	         			
				}
				else	/*else the pseudo is not correct*/
				{
			?>
					<script language="JavaScript">
						alert("give a correct pseudo");/*popup with javacript*/
						document.location.href = 'index.php';/*Rerouting in login page*/
					</script>
				<?php
				}			
					
			}
			 
		 		fclose($fp); 
		 }

	
	}
				?>